package cn.witsky.cdrService;

import java.io.File;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import cn.witsky.cdrService.config.AsnMoCallConfig;
import cn.witsky.cdrService.config.CdrConfig;
import cn.witsky.cdrService.config.FtpConfig;
import cn.witsky.cdrService.exception.StartUpException;
import cn.witsky.cdrService.util.CallFileUtil;
import cn.witsky.cdrService.util.FTPUtil;
import cn.witsky.cdrService.util.RedisUtil;

@SpringBootApplication
public class CdrServiceApplication implements ApplicationRunner {
	private static Logger logger = LoggerFactory.getLogger(CdrServiceApplication.class);	
	
	private static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
	
	@Autowired
	AsnMoCallConfig asnMoCallConfig;
	
	@Autowired
	FtpConfig ftpConfig;

	public static void main(String[] args) {
		if (args.length == 1 && args[0].equalsIgnoreCase("-v")) {
			cn.witsky.common.Version.showVersion();
			return;
		}
		SpringApplication app = new SpringApplication(CdrServiceApplication.class);
		app.run(args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		// TODO Auto-generated method stub
		logger.info("cdrService开始启动了......");
		boolean isValid = asnMoCallConfig.validate();
		if (!isValid) {
			throw (new StartUpException("moCall必填参数缺少配置"));
		}
		isValid = ftpConfig.validate();
		if (!isValid) {
			throw (new StartUpException("ftp配置缺少参数"));
		}
		this.execTask();
	}

	void execTask() {		
		LocalDateTime date = LocalDateTime.now();
		int minutes = date.getMinute();
		int second=date.getSecond();
		int count=minutes/CdrConfig.delayMinutes;
		int initialDelaySeconds = 0;
		if(minutes>count*CdrConfig.delayMinutes) {
			initialDelaySeconds=((count+1)*CdrConfig.delayMinutes-minutes)*CdrConfig.times-second;
		}else {
			if(second>0) {
				initialDelaySeconds=CdrConfig.delayMinutes*CdrConfig.times-second;
			}			
		}
		int delaySeconds=CdrConfig.delayMinutes*CdrConfig.times;
		logger.info("执行频率  initialDelay:{} delay:{} delayTimeUnit：{}",initialDelaySeconds,delaySeconds,TimeUnit.SECONDS);
		executorService.scheduleAtFixedRate(new Runnable() {
			public void run() {	
				logger.info("生成话单任务开始执行了");
				try {
					LocalDateTime now = LocalDateTime.now();
					boolean isSuc = false;
					StringBuilder fileName = new StringBuilder(CdrConfig.filePrefix);
					int seq = (now.getHour()*CdrConfig.times + now.getMinute()) / CdrConfig.delayMinutes;
					fileName.append(now.format(CdrConfig.df)).append("_").append(CdrConfig.numDf.format(seq)).append(CdrConfig.fileSuffix);
					int result= CallFileUtil.creatMoCallFile(now);
					if (result>0) {
						logger.info("生成话单{}文件成功了,开始进行ftp上传", fileName.toString());
						try {
							isSuc = FTPUtil.uploadFile(ftpConfig, new File(CdrConfig.moCallFileName), fileName.toString());
						} catch (Exception e) {
							isSuc = false;
							logger.error("ftp上传话单出现异常:", e);
						}
						if (!isSuc) {
							logger.warn("上传话单{}到ftp失败了", fileName.toString());
						} else {
							logger.warn("上传话单{}到ftp成功！清理redis话单数据", fileName.toString());
							RedisUtil.clearCdrListByLength(result);
						}
					}else if(result==0) {
						logger.warn("没有获取到需要生成话单的数据");
					}else {
						logger.warn("生成话单{}文件失败了", fileName.toString());
					}	
				}catch(Exception ex) {
					logger.error("定时执行任务出现异常:",ex);
				}							
			}
		}, initialDelaySeconds, delaySeconds,TimeUnit.SECONDS);
	}
}
